import { nextTick } from 'vue';
import * as echarts from 'echarts/core';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent } from 'echarts/components';
import { ElMessage } from 'element-plus';
import { costRecordApi } from '@/apis/costRecord';

// 注册 ECharts 组件
echarts.use([CanvasRenderer, PieChart, TitleComponent, TooltipComponent, LegendComponent]);

/**
 * 成本图表管理相关的hooks
 */
export const useCostChart = () => {
  // 初始化部门成本图表
  const initDepartmentChart = async () => {
    const chartDom = document.getElementById('departmentChart');
    if (!chartDom) return;
    
    const myChart = echarts.init(chartDom);
    
    // 默认数据
    let chartData = [
      { value: 35000, name: '研发部' },
      { value: 25000, name: '市场部' },
      { value: 20000, name: '销售部' },
      { value: 15000, name: '运营部' },
      { value: 10000, name: '行政部' },
      { value: 8000, name: '财务部' }
    ];
    
    try {
      // 调用API获取部门成本分析数据
      const now = new Date();
      const startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1).toISOString().split('T')[0];
      const endDate = new Date().toISOString().split('T')[0];
      
      const response = await costRecordApi.getCostAnalysis({
        startDate: startDate,
        endDate: endDate,
        analysisType: 1 // 1-按部门
      });
      
      // 数据转换
      if (response.data && Array.isArray(response.data)) {
        chartData = response.data.map(item => ({
          value: item.value || 0,
          name: item.name || '未知部门'
        }));
      }
    } catch (error) {
      console.error('获取部门成本数据失败:', error);
      ElMessage.error('获取部门成本数据失败');
    }
    
    const option = {
      title: {
        text: '',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        top: 'middle'
      },
      series: [
        {
          name: '部门成本',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: chartData
        }
      ]
    };
    
    myChart.setOption(option);
    
    // 响应式调整
    const handleResize = () => {
      myChart.resize();
    };
    
    window.addEventListener('resize', handleResize);
    
    // 返回清理函数
    return () => {
      window.removeEventListener('resize', handleResize);
      myChart.dispose();
    };
  };

  // 初始化成本项目图表
  const initCostItemChart = async () => {
    const chartDom = document.getElementById('costItemChart');
    if (!chartDom) return;
    
    const myChart = echarts.init(chartDom);
    
    // 默认数据
    let chartData = [
      { value: 30000, name: '人力成本' },
      { value: 25000, name: '营销费用' },
      { value: 20000, name: '差旅费用' },
      { value: 18000, name: '设备成本' },
      { value: 15000, name: '行政费用' },
      { value: 12000, name: '员工福利' }
    ];
    
    try {
      // 调用API获取成本项目分析数据
      const now = new Date();
      const startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1).toISOString().split('T')[0];
      const endDate = new Date().toISOString().split('T')[0];
      
      const response = await costRecordApi.getCostAnalysis({
        startDate: startDate,
        endDate: endDate,
        analysisType: 2 // 2-按成本项目
      });
      
      // 数据转换
      if (response.data && Array.isArray(response.data)) {
        chartData = response.data.map(item => ({
          value: item.value || 0,
          name: item.name || '未知项目'
        }));
      }
    } catch (error) {
      console.error('获取成本项目数据失败:', error);
      ElMessage.error('获取成本项目数据失败');
    }
    
    const option = {
      title: {
        text: '',
        left: 'center'
      },
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        top: 'middle'
      },
      series: [
        {
          name: '成本项目',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: '16',
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: chartData
        }
      ]
    };
    
    myChart.setOption(option);
    
    // 响应式调整
    const handleResize = () => {
      myChart.resize();
    };
    
    window.addEventListener('resize', handleResize);
    
    // 返回清理函数
    return () => {
      window.removeEventListener('resize', handleResize);
      myChart.dispose();
    };
  };

  // 渲染图表
  const renderCharts = async () => {
    await nextTick();
    // 由于initDepartmentChart和initCostItemChart现在是异步函数，需要await
    const [departmentChartCleanup, costItemChartCleanup] = await Promise.all([
      initDepartmentChart(),
      initCostItemChart()
    ]);
    
    // 返回清理函数
    return () => {
      if (departmentChartCleanup) departmentChartCleanup();
      if (costItemChartCleanup) costItemChartCleanup();
    };
  };

  return {
    renderCharts,
    initDepartmentChart,
    initCostItemChart
  };
};

export default useCostChart;